package com.ai.tikai.utils;

import com.ai.tikai.entity.SuggestionsLable;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
@Slf4j
@Converter
public class SuggestionDetailsConverter implements AttributeConverter<List<SuggestionsLable>, String> {
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 将实体属性(Java对象)转换为数据库列(JSON字符串)
     * @param attribute the entity attribute value to be converted
     * @return the converted data to be stored in the database column
     */
    @Override
    public String convertToDatabaseColumn(List<SuggestionsLable> attribute) {
        if (attribute == null || attribute.isEmpty()) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(attribute);
        } catch (JsonProcessingException e) {
            log.error("Could not convert list of SuggestionDetail to JSON string.", e);
            throw new IllegalArgumentException("Error converting list to JSON", e);
        }
    }

    /**
     * 将数据库列(JSON字符串)转换为实体属性(Java对象)
     * @param dbData the data from the database column to be converted
     * @return the converted value to be stored in the entity attribute
     */
    @Override
    public List<SuggestionsLable> convertToEntityAttribute(String dbData) {
        if (dbData == null || dbData.trim().isEmpty()) {
            return Collections.emptyList();
        }
        try {
            // 使用 TypeReference 来处理泛型列表
            return objectMapper.readValue(dbData, new TypeReference<List<SuggestionsLable>>() {});
        } catch (IOException e) {
            log.error("Could not convert JSON string to list of SuggestionDetail.", e);
            throw new IllegalArgumentException("Error converting JSON to list", e);
        }
    }
}
